home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: nntp.coast.net!torn!info!rede4740
- From: rede4740@mach1.wlu.ca (Chris Redekop u)
- Subject: Q: gets, getch, and stdin
- X-Newsreader: TIN [version 1.1 PL6]
- Message-ID: <DnoC9w.Eq9@info.uucp>
- Nntp-Posting-Host: mach1.wlu.ca
- Sender: news@info.uucp (news management)
- Organization: Wilfrid Laurier University
- Date: Sun, 3 Mar 1996 04:25:07 GMT
-
-
- Hi. I'm trying to teach myself C with the help of 'Teach Yourself C In
- 21 Days'. Everything was going fine until day 14, 'Working with the
- Screen, Printer, and Keyboard'. On page 319 (in case anyone reading this
- has the book), it talked about how using scanf can leave unwanted
- characters in stdin. It offered this function as a way to clear stdin:
-
- void clear_kb(void)
- {
- char junk[80];
- gets(junk);
- }
-
- I thought to myself, 'That might work, but it uses a whole array to do
- it. Instead of clearing stdin by reading a whole string, I should be
- able to clear it one chartacter at a time, by using getch(). Then I
- would only need one local variable of type char (or int).' So I tried this:
-
- void clear_kb(void)
- {
- char ch;
-
- while ((ch = getch()) != '\r')
- ;
- }
-
- This didn't work, so after I tried a few different things, I found that
- this works:
-
- void clear_kb(void)
- {
- char ch;
-
- while ((ch = getchar()) != '\n')
- ;
- }
-
- This is what confuses me. I can't understand why the third function
- works, and not the second. As well, the third function does not output
- the cleared characters to the screen, even though getchar provides input
- with echo. I think this all has something to do with (what is to me) the
- mysterious nature of stdin. Unfortunately, this was not as clearly
- covered in the book as I needed. If anyone can shed some light on this
- elementary subject I would very much aprreciate it.
-
- Thank you,
- Chris Redekop
-
-